package org.flycloud.web.sso.common;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class SessionCache {

	private JedisPool jedis;

	public SessionCache(JedisPool jedis) {
		this.jedis = jedis;
	}

	public UserSession getToken(HttpServletRequest request) {
		return getToken(SystemSession.getTokenString(request));
	}

	public void setToken(String token, UserSession us) {
		Jedis j = jedis.getResource();
		j.set(token, JSON.toJSONString(us));
		j.close();
	}

	// 在redis中查找token对应的UserSession
	public UserSession getToken(String token) {
		Jedis j = jedis.getResource();
		UserSession us = JSON.parseObject(j.get(token), new TypeReference<UserSession>() {
		});
		j.close();
		return us;
	}

	public boolean hasToken(String token) {
		Jedis j = jedis.getResource();
		boolean b = j.get(token) != null;
		j.close();
		return b;
	}

	public void delToken(String token) {
		Jedis j = jedis.getResource();
		j.del(token);
		j.close();
	}

	public void setByUserName(String token, UserSession us) {
		Jedis j = jedis.getResource();
		j.set(token, JSON.toJSONString(us));
		j.close();
	}

	// 在redis中查找token对应的UserSession
	public UserSession getByUserName(String token) {
		Jedis j = jedis.getResource();
		UserSession us = JSON.parseObject(j.get(token), new TypeReference<UserSession>() {
		});
		j.close();
		return us;
	}
}
